﻿using Ace;
using MalwarePatch.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MalwarePatch.CliTools
{
  internal class SilentUpdater
  {
    public const string
      SilentUpdateParameter = "--silent-update",
      DisallowAllParameter = "--disallow-all",
      AllowAllParameter = "--allow-all",
      ProxyParameter = "--proxy";

    public static bool TryParse(string[] args)
    {
      var dictionary = string.Join(" ", args).SplitToDictionary(" ", "=", true);
      var proxy = null as string;
      //if (dictionary.ContainsKey(ProxyParameter))
      //{
      //    proxy = dictionary[ProxyParameter];
      //}

      try
      {
        if (dictionary.ContainsKey(SilentUpdateParameter) && !BuildConfig.IsUnbundled)
        {
          Update(dictionary, proxy)?.Wait();
        }
        else if (dictionary.ContainsKey(DisallowAllParameter))
        {
          DisallowAll().Wait();
        }
        else if (dictionary.ContainsKey(AllowAllParameter))
        {
          AllowAll().Wait();
        }
        else
        {
          return false;
        }
      }
      catch
      {
        return false;
      }

      return true;
    }
    public static Task Update(Dictionary<string, string> dictionary, string proxy = null)
    {
      var checker = new VersionChecker
      {
        Proxy = proxy
      };
      if (checker.HasNewVersion)
      {
        return Task.Run(() =>
        {
          var arguments = new Dictionary<string, string>
            {
              { Updater.RestartParameter, null }
            };
          arguments.AddRange(dictionary);
          arguments.Remove(SilentUpdateParameter);

          var finalArguments = string.Join(" ", arguments.Select(item =>
            {
              if (item.Value is null)
              {
                return item.Key;
              }
              else
              {
                return $"{item.Key}={item.Value}";
              }
            }));
          var updater = new Updater
          {
            Proxy = proxy,
            RestartParameters = finalArguments == Updater.RestartParameter ? "" : finalArguments
          };
          updater.DownloadUpdate().Wait();
          if (File.Exists(Updater.UpdateFileName))
          {
            var startInfo = new ProcessStartInfo(Updater.UpdateFileName)
            {
              Arguments = $"{Updater.UpdateParameter}={(Process.GetCurrentProcess().MainModule.FileName.GetFileName()).Quotes()} {updater.RestartParameters}",
              WorkingDirectory = Environment.CurrentDirectory,
              UseShellExecute = false,
            };
            Process.Start(startInfo);
          }
        });
      }
      else
      {
        return null;
      }
    }
    public static Task DisallowAll()
    {
      return Task.Run(() =>
      {
        BuiltInCertificates.All.ForEach(c => c.Disallow());
      });
    }
    public static Task AllowAll()
    {
      return Task.Run(() =>
      {
        BuiltInCertificates.All.ForEach(c => c.Allow());
      });
    }
  }
}
